package com.gjy.util.poi;

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gjy
 * @version 1.0
 * @since 2024-03-04 09:42:02
 */
public class JxlsUtils {

    public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
        Context context = PoiTransformer.createInitialContext();
        if (model != null) {
            for (Map.Entry<String,Object> entry:model.entrySet()){
                context.putVar(entry.getKey(), entry.getValue());
            }
        }
        JxlsHelper jxlsHelper = JxlsHelper.getInstance();
        Transformer transformer  = jxlsHelper.createTransformer(is, os);

        JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator();
        Map<String, Object> funcs = new HashMap<>();
        //添加自定义功能
        funcs.put("utils", new JxlsUtils());
        //evaluator.getJexlEngine().setFunctions(funcs)

        //这里之前的evaluator.getJexlEngine().setFunctions(functionMap);是有问题的，从下载下来的例子中也可以看到此句话是被注释的。因为这里的jexlEngine使用的setFunctions是jexl2中的方法，而2.6.0后开始使用的是jexl3。我用的version是2.10.0
        JexlBuilder jb = new JexlBuilder();
        jb.namespaces(funcs);
        JexlEngine je = jb.create();
        evaluator.setJexlEngine(je);

        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
    }

    public static void exportExcel(File xls, File out, Map<String, Object> model) throws  IOException {
        exportExcel(new FileInputStream(xls), new FileOutputStream(out), model);
    }

    public static void exportExcel(String templateName, OutputStream os, Map<String, Object> model) throws IOException {
        File template = getTemplate(templateName);
        if (template != null) {
            exportExcel(new FileInputStream(template), os, model);
        }
    }


    /**
     * 获取excel模板文件路径
     *
     * @param name 模板文件路径
     * @return 返回该文件
     */

    public static File getTemplate(String name) {
        File template = new File(name);
        if (template.exists()) {
            return template;
        }
        return null;
    }

    /**
     *  excel的判断
     * @param b  选择1还是选择2
     * @param o1 比较对象1
     * @param o2  比较对象2
     * @return 比较后的对象
     */
    public Object ifElse(boolean b, Object o1, Object o2) {
        return b ? o1 : o2;
    }
}
